package com.bw.demo.valid.validator;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bw.demo.valid.anno.EnumValid;

/**
 * 枚举校验
 * @author tao zhisheng
 *
 */
public class EnumConstraintValidator implements ConstraintValidator<EnumValid, String> 
{
	
	private Logger logger = LoggerFactory.getLogger(EnumConstraintValidator.class);

	/** 保存枚举中的值*/
	private Set<String> values = new HashSet<String>();
	
	@Override
	public void initialize(EnumValid constraintAnnotation) 
	{
		// 获取校验的enum类
		Class<?> enumClass = constraintAnnotation.target();
		// 获取需要校验的enum类里取的值的字段名
		String enumType = constraintAnnotation.enumType();
		// 获取方法
		String methodName = "get" + enumType.substring(0, 1).toUpperCase() + enumType.substring(1);
		String result = null;
		Method method = null;
		if (enumClass.isEnum()) 
		{
			Object[] enums = enumClass.getEnumConstants();
			for (Object o : enums) 
			{
				try 
				{
					method = o.getClass().getDeclaredMethod(methodName);
					result = (String) method.invoke(o);
					values.add(result);
				} catch (Exception e) 
				{
					logger.error("枚举校验异常：{}", e);
				} 
			}
		}
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) 
	{
		// 为空时，直接放行
		if (value == null || "".equals(value.trim())) 
		{
			return true;
		}
		if (values.contains(value)) 
		{
			return true;
		}
		return false;
	}

}
